var fs = require('fs')
var path = require('path')
var uglifyjs = require("uglify-js");
var cssmin = require('cssmin');

function change(limit) {
  return (limit.length / 1024).toFixed(0) + "kb";
}

var fileArr = [];
var initialPath = './dist';
var fileEach = function (dir) {
  var files = fs.readdirSync(dir);
  files.forEach(function (file) {
    //全部路径
    var qfile = path.resolve(dir, file);
    if ((file.indexOf(".js") > -1 || file.indexOf(".css") > -1) && file.indexOf(".json") == -1) {
      fileArr.push({
        file,
        qfile
      });
    }
  });
  for (var i = 0; i < fileArr.length; i++) {
    var origCode = fs.readFileSync(fileArr[i].qfile, 'utf8');
    let result = "";
    let fileInfo = fileArr[i].file;
    if (fileInfo.indexOf(".js") > -1 && fileInfo.indexOf(".json") == -1) {
      result = uglifyjs.minify(origCode).code;
      fs.writeFileSync('dist/' + fileArr[i].file, result);
    }else if(fileInfo.indexOf(".css") > -1){
      result = cssmin(origCode);
      fs.writeFileSync('dist/' + fileInfo, result);
    }

    console.log('压缩 ，dist/' + fileInfo,change(result));
  }
}

fileEach(initialPath);
